package 栈和队列.逆波兰表达式;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/29 16:06
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        String[] tokens = {"2","1","+","3","*"};
        System.out.println(evalRPN(tokens));
    }

    //所谓的逆波兰表达式其实就是把算式的后缀表达式转换为中缀表达式进行计算
    public static int evalRPN(String[] tokens) {
        List<String> list = new ArrayList<>();
        list.add("+");
        list.add("-");
        list.add("*");
        list.add("/");
        Stack<String> stack = new Stack<>();
        int result = 0;
        for (int i = 0; i < tokens.length; i++) {
            if (list.contains(tokens[i])){
                String pop1 = stack.pop();
                String pop2 = stack.pop();
                String symbol = tokens[i];
                int calculateNum = calculate(pop1, pop2, symbol);
                result = calculateNum;
                stack.push(String.valueOf(calculateNum));
            }else {
                stack.push(tokens[i]);
            }
        }
        return result;
    }

    public static int calculate(String pop1,String pop2,String symbol){
        Integer num1 = Integer.valueOf(pop1);
        Integer num2 = Integer.valueOf(pop2);
        int result = 0;
        if (symbol == "+"){
            result = num2 + num1;
        }else if (symbol == "-"){
            result = num2 - num1;
        }else if (symbol == "*"){
            result = num2 * num1;
        }else if (num1 != 0 && symbol == "/"){
            result = num2 / num1;
        }
        return result;
    }
}
